package com.web.core.async.redis;

import com.web.core.cache.ICache;
import com.web.core.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 刷新缓存监听器
 * 
 * @author zhengj
 * @since 2016年3月31日 1.0
 */
@Component
public class CacheRefreshListener implements ApplicationContextAware
{
	private static Logger logger = LoggerFactory.getLogger(CacheRefreshListener.class);
	
	private ApplicationContext ctx;
	
	public CacheRefreshListener()
	{
	}
	
	public void handle(Object object)
	{
		logger.info("收到消息：{}－{}", object, object.getClass().getName());
		if (!(object instanceof String))
			return;
		
		String text = (String)object;
		String[] texts = text.split(Const.CACHE_SPLIT);
		if (texts.length == 1)
		{
			String bean = texts[0];
			try
			{
				InitializingBean cache = ctx.getBean(bean, InitializingBean.class);
				cache.afterPropertiesSet();
				logger.info("刷新缓存[bean={}]", bean);
			}
			catch (BeansException e)
			{
				logger.warn("找不到 bean=" + bean);
			}
			catch (Exception e)
			{
				logger.info("刷新缓存发生错误－", e);
			}
		}
		else if (texts.length == 2)
		{
			String bean = texts[0];
			try
			{
				Integer id = Integer.valueOf(texts[1]);
				ICache cache = ctx.getBean(bean, ICache.class);
				cache.put(id);
				logger.info("更新缓存[bean={}, id={}]", bean, id);
			}
			catch (NumberFormatException e)
			{
				logger.info("无效整数－", texts[1]);
			}
			catch (BeansException e)
			{
				logger.warn("找不到 bean=" + bean);
			}
			catch (Exception e)
			{
				logger.info("更新缓存发生错误－", e);
			}
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException
	{
		this.ctx = ctx;
	}
	
	
}
